package com.hup.minicontroller.server.model;

import android.content.SharedPreferences;

import com.alibaba.fastjson.JSON;
import com.hup.minicontroller.common.constant.NetConstant;
import com.hup.minicontroller.common.framework.SpUtil;
import com.hup.minicontroller.common.model.dto.ControlConfigDto;
import com.hup.minicontroller.server.constant.AppConstant.SPKey;
import com.hup.minicontroller.server.service.MainService;

import lombok.Data;

/**
 * 控制配置
 */
@Data
public class ControlConfig {
    /**
     * 取值范围,修改时需要同时修改strings.xml中的值
     */
    public static final Integer[] FPS = new Integer[]{10, 30, 60};
    public static final Integer[] SCREEN_SIZE = new Integer[]{25, 50, 75, 100};
    public static final Integer[] SCREEN_QUALITY = new Integer[]{10, 25, 50, 100};

    /**
     * 是否能启动录屏
     * 客户端不可控字段
     */
    private boolean canEnableScreen = false;

    /**
     * 显示光标
     * 客户端不可控字段
     */
    private boolean showCursor = true;
    /**
     * 允许控制:触摸,发送按键消息
     * 客户端不可控字段
     */
    private boolean enableControl = true;
    /**
     * 传输图像
     */
    private boolean enableScreen = true;
    /**
     * {@link NetConstant#FPS}
     */
    private int fps = NetConstant.FPS[NetConstant.DEFAULT_FPS_INDEX];
    /**
     * {@link NetConstant#SCREEN_SIZE}
     */
    private int screenSize = NetConstant.SCREEN_SIZE[NetConstant.DEFAULT_SCREEN_SIZE_INDEX];
    /**
     * {@link NetConstant#SCREEN_QUALITY}
     */
    private int screenQuality = NetConstant.SCREEN_QUALITY[NetConstant.DEFAULT_SCREEN_QUALITY_INDEX];

    public ControlConfigDto toDto() {
        return JSON.toJavaObject((JSON) JSON.toJSON(this), ControlConfigDto.class);
    }

    /**
     * 将客户端发送的配置应用到本程序;
     *
     * @return 是否回复发送者修改后的状态:true-回复发送者(如不能开启图像)
     */
    public boolean applyClientReq(ControlConfigDto dto) {
        enableScreen = dto.isEnableScreen();
        SpUtil.apply(MainService.getSp(), SPKey.ENABLE_SCREEN, enableScreen);

        fps = NetConstant.getSafeFps(dto.getFps());
        SpUtil.apply(MainService.getSp(), SPKey.FPS, fps);

        screenSize = NetConstant.getSafeScreenSize(dto.getScreenSize());
        SpUtil.apply(MainService.getSp(), SPKey.SCREEN_SIZE, screenSize);

        screenQuality = NetConstant.getSafeScreenQuality(dto.getScreenQuality());
        SpUtil.apply(MainService.getSp(), SPKey.SCREEN_QUALITY, screenQuality);

        if (!canEnableScreen && enableScreen) {
            enableScreen = false;
            return true;
        }
        return false;
    }

    public void loadConfig(SharedPreferences sp) {
        enableScreen = sp.getBoolean(SPKey.ENABLE_SCREEN, enableScreen);
        fps = sp.getInt(SPKey.FPS, fps);
        screenSize = sp.getInt(SPKey.SCREEN_SIZE, screenSize);
        screenQuality = sp.getInt(SPKey.SCREEN_QUALITY, screenQuality);
    }

}
